/*
 * Copyright (c) 2012 Robert Burrell Donkin robertburrelldonkin.name
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
 * and associated documentation files (the "Software"), to deal in the Software without restriction, 
 * including without limitation the rights to use, copy, modify, merge, publish, distribute, 
 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 
 * is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or 
 * substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING 
 * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 * 
 */
package name.robertburrelldonkin.alfie;

import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class Hold<Subject> extends MediaryCog<Future<Subject>, Subject> {

	private static final int COMPLETE_WAIT = 10;

	public static final int DEFAULT_MAX_TO_CHECK = 50;
	
	private final Queue<Future<Subject>> hold;
	
	public Hold(BlockingQueue<Message<Future<Subject>>> in,
			BlockingQueue<Message<Subject>> out) {
		this(in, out, DEFAULT_TIMEOUT, DEFAULT_MAX_TO_CHECK);
	}
	
	public Hold(BlockingQueue<Message<Future<Subject>>> in,
			BlockingQueue<Message<Subject>> out, int timeoutInMillis, final int maxToCheck) {
		super(in, out, timeoutInMillis);
		hold = new ArrayDeque<Future<Subject>>();
	}

	@Override
	protected void communicate(Future<Subject> future) {
		if (future == null) {
			System.out.println("Null future");
		} else if (future.isDone()) {
			forward(future);
		} else {
			hold.add(future);
		}
	}

	@Override
	protected void afterDoHook() {
		super.afterDoHook();
		checkFuture();
	}

	private void checkFuture() {
		while (!hold.isEmpty() && hold.peek().isDone()) {
			final Future<Subject> future = hold.poll();
			forward(future);
		}
	}

	@Override
	protected void awaitingInputHook() {
		super.awaitingInputHook();
		forwardDone();
	}

	private void forwardDone() {
		for (final Iterator<Future<Subject>> it=hold.iterator(); it.hasNext();) {
			final Future<Subject> next = it.next();
			if (next.isDone()) {
				it.remove();
				forward(next);
			}
		}
	}

	private void forward(Future<Subject> future) {
		try {
			final Subject subject = future.get();
			out(subject);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			final Throwable cause = e.getCause();
			if (cause instanceof WithSeverity) {
				final WithSeverity withSeverity = (WithSeverity) cause;
				switch (withSeverity.severity()) {
				case WARNING:
					System.out.println("[FAIL] " + e.getMessage());
					break;
				case FATAL:
				default:
					printFullTraces(e);
					break;
				}
			} else {
				printFullTraces(e);
			}
		}
	}

	private void printFullTraces(ExecutionException e) {
		e.printStackTrace();
		e.getCause().printStackTrace();
	}

	@Override
	protected void completeWorkHook() {
		super.completeWorkHook();
		while (!hold.isEmpty()) {
			try {
				hold.peek().get(COMPLETE_WAIT, TimeUnit.MILLISECONDS);
			} catch (InterruptedException e) {
			} catch (ExecutionException e) {
			} catch (TimeoutException e) {}
			forwardDone();
		}
	}

	
}
